package com.kuangstudy.controller;

import com.kuangstudy.constant.RedisConstants;
import com.kuangstudy.entity.User;
import com.kuangstudy.service.focus.AttentionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

/**
 * @author renyitong
 * @version 1.0.0
 * @createTime 2023年09月19日
 * @Description
 */
@RestController
@Api(tags = "帖子点赞&收藏&举报")
public class ArticleLikeController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AttentionService attentionService;


    @ApiOperation("用户点赞")
    @PostMapping("/user/click/like")
    public String userLikeArticle(Long bbsId, Long userId) {
        try {
            Long add = this.redisTemplate.opsForSet().add(RedisConstants.USER_LIKE_ARTICLE_SET + bbsId, userId);
            return add > 0 ? "点赞成功" : "你已经点赞过了...";
        } catch (Exception ex) {
            throw new RuntimeException("服务器忙，请稍后再试...");
        }
    }


    @ApiOperation("用户取消点赞")
    @PostMapping("/user/click/unlike")
    public String userUnLikeArticle(Long bbsId, Long userId) {
        try {
            Long add = this.redisTemplate.opsForSet().remove(RedisConstants.USER_LIKE_ARTICLE_SET + bbsId, userId);
            return add > 0 ? "取消点赞成功" : "你已经取消过了...";
        } catch (Exception ex) {
            throw new RuntimeException("服务器忙，请稍后再试...");
        }
    }


    @ApiOperation("查询帖子的总点赞人数")
    @PostMapping("/user/total/like")
    public String userTotalLikes(Long bbsId) {
        try {
            Long size = this.redisTemplate.opsForSet().size(RedisConstants.USER_LIKE_ARTICLE_SET + bbsId);
            return size > 0 ? "共有" + size + "人点赞" : "暂时还无人点赞...";
        } catch (Exception ex) {
            throw new RuntimeException("服务器忙，请稍后再试...");
        }
    }


    @PostMapping("/user/list/likes")
    @ApiOperation("获取点赞成员")
    public List<User> userListLikes(Long bbsId) {
        try {
            Set<Long> members = this.redisTemplate.opsForSet().members(RedisConstants.USER_LIKE_ARTICLE_SET + bbsId);
            List<User> userList = attentionService.getUserInfo(members);
            return userList;
        } catch (Exception ex) {
            throw new RuntimeException("服务器忙，请稍后再试...");
        }
    }

    @ApiOperation("判断用户是否点赞过")
    @PostMapping("/user/ismember/like")
    public String userIsMemberLike(Long bbsId, Long userId) {
        try {
            Boolean member = this.redisTemplate.opsForSet().isMember(RedisConstants.USER_LIKE_ARTICLE_SET + bbsId, userId);
            return member ? "点赞过了" : "您还没有点赞";
        } catch (Exception ex) {
            throw new RuntimeException("服务器忙，请稍后再试...");
        }
    }

}
